package org.example.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    public static final String JWT_SECRET = "lianchengll";
    public static final long EXPIRE_TIME = 1000 * 60 * 5; // 5分钟

    public static String createToken(String subject, long expireTime) {
        return Jwts.builder()
                //头部
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //载荷
                //用户标识信息//过期时间:5分钟//密钥
                //令牌的类型为JWT令牌//签名的加密算法HS256
                //唯一标识
                .setId(UUID.randomUUID().toString())
                .setIssuer("laoli")//签发人
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .setSubject(subject)
                // 签名
                .signWith(SignatureAlgorithm.HS256, JWT_SECRET)
                .compact();
    }

    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(JWT_SECRET)
                .parseClaimsJws(token)
                .getBody();
    }
}
